package com.extension.company.common.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import com.extension.company.Constant;

/*
 * 缓存管理器
 */
public class SharedPreferenceUtils {
	private static Context mContext;
	private static SharedPreferences sp = null;

	public static void init(Context context) {
		mContext = context;
		sp = context.getSharedPreferences(Constant.SP_FILE_NAME, Context.MODE_PRIVATE);

	}

	/**
	 * 向sharepreferences存入键值对
	 */
	public static boolean addCache(String[] keys, Object[] values) {
		if (keys.length != values.length) {
			return false;
		}

		SharedPreferences sp = mContext.getSharedPreferences(Constant.SP_FILE_NAME, Context.MODE_PRIVATE);
		Editor editor = sp.edit();
		for (int i = 0; i < keys.length; i++) {
			if (values[i] instanceof String) {
				editor.putString(keys[i], (String) values[i]);
			} else if (values[i] instanceof Boolean) {
				editor.putBoolean(keys[i], (Boolean) values[i]);
			} else if (values[i] instanceof Integer) {
				editor.putInt(keys[i], (Integer) values[i]);
			} else if (values[i] instanceof Long) {
				editor.putLong(keys[i], (Long) values[i]);
			} else if (values[i] instanceof Float) {
				editor.putFloat(keys[i], (Float) values[i]);
			}
		}
//		editor.commit();
		editor.apply();
		return true;
	}

	public static String getString(String key, String defaultValue) {
		if (sp == null) {
			return defaultValue;
		}
		return sp.getString(key, defaultValue);
	}

	public static boolean getBoolean(String key, boolean defaultValue) {
		if (sp == null) {
			return defaultValue;
		}
		return sp.getBoolean(key, defaultValue);
	}

	public static int getInt(String key) {
		if (sp == null) {
			return 0;
		}
		return sp.getInt(key, 0);
	}

	public static long getLong(String key) {
		if (sp == null) {
			return 0;
		}
		return sp.getLong(key, 0L);
	}

	public static boolean remove(String key) {
		if (sp == null) {
			return false;
		}
		Editor editor = sp.edit();
		editor.remove(key);
//		editor.commit();
		editor.apply();
		return true;
	}
}
